<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="sAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roleList">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="sDisttib(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="sEdit(scope.row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="sDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                :page-size="pageParams.pagesize"
                :current-page="pageParams.page"
                :page-sizes="[2, 3, 5, 10]"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit? '编辑角色' : '新增角色'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="hCancel">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
        :visible.sync="showDialogAssign"
        @close="aClose"
      >
        <assign-permission
          ref="assignPermission"
          :cur-id="curId"
          @close="close"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignPermission from './assignPermission'
import { settingslist, delSettings, addSettings, getSettingById, updateSettingById } from '@/api/settings'
export default {
  name: 'Settings',
  components: {
    assignPermission
  },
  data() {
    return {
      // 分配弹框
      showDialogAssign: false,
      // 所有角色列表
      roleList: [],
      pageParams: {
        page: 1, // 查询第一页
        pagesize: 2 // 每页两条  --- 要与pagination中page-size一致
      },
      total: 0, // 总的数据条数
      showDialog: false, // 控制弹框的显示
      // 弹框的数据
      roleForm: {
        name: '',
        description: ''
      },
      // 校验规则
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: []
      },
      // 是否是编辑弹框
      isEdit: false,
      // 当前id
      curId: ''
    }
  },
  computed: {
    // 最大页数
    maxNum() {
      return Math.ceil(this.total / this.pageParams.pagesize)
    },
    // 最后一页是不是满了
    isFull: function() {
      return this.total % this.pageParams.pagesize === 0
    }
  },

  created() {
    // 刷新页面
    this.getSettingslist()
  },
  methods: {
    // 获取所有角色列表
    async getSettingslist() {
      try {
        const { data: res } = await settingslist(this.pageParams)
        // console.log(res.data)
        this.roleList = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 分页组件页码sise变化
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // (1)修改每页条数
      this.pageParams.pagesize = val
      // (2)刷新列表
      this.getSettingslist()
    },
    // 分页组件page值变化
    handleCurrentChange(page) {
      // console.log(`当前页: ${page}`)
      // (1)修改每页条数
      this.pageParams.page = page
      // (2)刷新列表
      this.getSettingslist()
    },
    // 分配权限
    sDisttib(id) {
      // console.log(id, '分配选定的id')
      this.curId = id
      this.showDialogAssign = true
      setTimeout(() => {
        this.$refs.assignPermission.setPermissionsList()
      }, 0)
    },
    // 编辑按钮
    async sEdit(id) {
      // console.log(id, '编辑选定的id')
      this.showDialog = true
      this.isEdit = true
      try {
        const res = await getSettingById(id)
        // console.log(res)
        // 数据填充
        this.roleForm = res.data.data
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑
    async doEdit() {
      try {
        await updateSettingById(this.roleForm)
        // console.log(res)
        this.$message.success('"更新角色详情成功"')
        this.getSettingslist()
      } catch (error) {
        console.log(error)
      }
    },
    // 删除
    sDel(id) {
      // console.log(id, '删除选定的id')
      this.$confirm('删除当前的角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        await delSettings(id)
        // 2. 如果当前表格中只有一条，删除之后自动请求上一页数据
        if (this.roleList.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        this.getSettingslist()
        // console.log(res)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 新增角色,打开弹窗
    sAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    // 新增
    async doadd() {
      try {
        await addSettings(this.roleForm)
        // console.log(res)
        this.$message.success('新增角色成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 确定按键
    hSubmit(id) {
      this.$refs.roleForm.validate((valid) => {
        if (!valid) return // 如果表单验证不通过，直接return
        // 通过的代码
        this.isEdit ? this.doEdit() : this.doadd()
        setTimeout(() => {
          this.showDialog = false
        }, 0)
        this.getSettingslist()
      })
    },
    // 取消新增
    hCancel() {
      this.showDialog = false
    },
    // 弹框关闭
    hClose() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    },
    // close
    close() {
      this.showDialogAssign = false
    },
    // aClose
    aClose() {
      this.$refs.assignPermission.resetForm()
    }
  }}
</script>

<style>

</style>
